<template>
  <div class="seller-page">
    <div v-if="loading" class="loading-container">
      <p>正在加载商家信息...</p>
    </div>

    <div v-else-if="!seller" class="error-container">
      <p>商家信息不存在</p>
      <button @click="goBack" class="back-button">返回</button>
    </div>

    <div v-else class="detail-content">
      <div class="seller-content">
        <!-- 商家信息头部 -->
        <div class="seller-header">
          <button @click="goBack" class="back-button">← 返回</button>
          <div class="seller-info">
            <img v-if="seller.logoUrl" :src="seller.logoUrl" :alt="seller.shopName" class="seller-logo" />
            <div class="seller-details">
              <h1 class="seller-name">{{ seller.shopName || '未知店铺' }}</h1>
              <div class="seller-contact">联系人：{{ seller.contactPerson || '暂无' }}</div>
              <div class="seller-phone">联系电话：{{ seller.contactPhone || '暂无' }}</div>
              <div class="seller-address">店铺地址：{{ seller.address || '暂无' }}</div>
            </div>
          </div>
        </div>

        <!-- 搜索和分类区域 -->
        <div class="search-section">
          <div class="search-area">
            <input
              type="text"
              v-model="searchKeyword"
              placeholder="搜索商品"
              class="search-input"
              @keyup.enter="handleSearch"
              @input="handleSearchInput"
            >
            <div class="category-tabs">
              <div
                class="category-tab"
                :class="{ active: selectedCategoryId === null }"
                @click="selectCategory(null)"
              >
                全部分类
              </div>
              <div
                v-for="category in categories"
                :key="category.categoryId"
                class="category-tab"
                :class="{ active: selectedCategoryId === category.categoryId }"
                @click="selectCategory(category.categoryId)"
              >
                {{ category.categoryName }}
              </div>
            </div>
          </div>
        </div>

        <!-- 商品列表 -->
        <div class="product-list">
          <h3>商品列表</h3>
          <div v-if="products.length === 0" class="no-products">
            {{ loadingProducts ? '正在加载商品...' : '暂无商品' }}
          </div>
          <div v-else class="products-grid">
            <div
              v-for="product in products"
              :key="product.productId"
              class="product-card"
              @click="goToProductDetail(product.productId)"
            >
              <div class="product-image">
                <img :src="product.productImage" :alt="product.productName" />
              </div>
              <div class="product-info">
                <div class="product-name">{{ product.productName }}</div>
                <div class="product-price">￥{{ product.productPrice}}</div>
                <div class="product-stock">库存：{{ product.productStock }}件</div>
              </div>
            </div>
          </div>
        </div>

        <!-- 分页 -->
        <div v-if="products.length > 0" class="pagination">
          <button
            @click="changePage(currentPage - 1)"
            :disabled="currentPage <= 1"
            class="page-btn"
          >
            上一页
          </button>
          <span class="page-info">{{ currentPage }} / {{ totalPages }}</span>
          <button
            @click="changePage(currentPage + 1)"
            :disabled="currentPage >= totalPages"
            class="page-btn"
          >
            下一页
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import http from '../api/http'

export default {
  name: 'SellerPage',
  setup() {
    const route = useRoute()
    const router = useRouter()
    const sellerId = ref(Number(route.params.id))
    const seller = ref(null)
    const categories = ref([])
    const products = ref([])
    const loading = ref(true)
    const loadingProducts = ref(false)
    const searchKeyword = ref('')
    const selectedCategoryId = ref(null)
    const currentPage = ref(1)
    const pageSize = ref(10)
    const totalPages = ref(1)

    // 获取商家信息
    const fetchSellerInfo = async () => {
      try {
        // 使用http实例而非axios，确保认证token正确传递
        // 移除/api前缀，http.js中已配置baseURL
        const response = await http.get('/seller/querySellerById', { 
          params: { id: sellerId.value } 
        })
        // 根据http.js响应拦截器，已直接返回response.data
        seller.value = response
      } catch (error) {
        console.error('获取商家信息失败:', error)
      }
    }

    // 获取商家分类
    const fetchSellerCategories = async () => {
      try {
        // 使用http实例而非axios，确保认证token正确传递
        // 移除/api前缀，http.js中已配置baseURL
        const response = await http.get(`/category/getSellerCategory/${sellerId.value}`)
        // 根据http.js响应拦截器，已直接返回response.data
        categories.value = response
      } catch (error) {
        console.error('获取商家分类失败:', error)
      }
    }

    // 获取商家商品
    const fetchSellerProducts = async (page = 1, keyword = '', categoryId = null) => {
      loadingProducts.value = true
      try {
        const params = {
          sellerId: sellerId.value,
          page: page,
          size: pageSize.value,
          status: 1 // 只显示上架商品
        }

        if (keyword) {
          params.keyword = keyword
        }
        if (categoryId !== null) {
          params.categoryId = categoryId
        }

        // 使用http实例而非axios，确保认证token正确传递
        // 移除/api前缀，http.js中已配置baseURL
        const response = await http.get('/product/query', { params })
        // 根据http.js响应拦截器，已直接返回response.data
        products.value = response.list || []
        // 清理图片URL中的反引号和空格
        products.value = products.value.map(product => ({
          ...product,
          productImage: product.productImage ? product.productImage.replace(/[`\s]/g, '') : ''
        }))
        totalPages.value = Math.ceil(response.total / pageSize.value) || 1
        currentPage.value = page
      } catch (error) {
        console.error('获取商家商品失败:', error)
      } finally {
        loadingProducts.value = false
      }
    }

    // 搜索商品
    const handleSearch = () => {
      currentPage.value = 1  // 重置到第一页
      fetchSellerProducts(1, searchKeyword.value, selectedCategoryId.value)
    }

    // 搜索输入处理（实时搜索，带防抖）
    let searchTimeout = null
    const handleSearchInput = () => {
      // 清除之前的定时器
      if (searchTimeout) {
        clearTimeout(searchTimeout)
      }

      // 设置新的定时器，延迟500ms执行搜索
      searchTimeout = setTimeout(() => {
        currentPage.value = 1
        fetchSellerProducts(1, searchKeyword.value, selectedCategoryId.value)
      }, 500)
    }

    // 分类选择处理
    const selectCategory = (categoryId) => {
      selectedCategoryId.value = categoryId
      currentPage.value = 1  // 重置到第一页
      fetchSellerProducts(1, searchKeyword.value, categoryId)
    }

    // 切换页码
    const changePage = (page) => {
      if (page >= 1 && page <= totalPages.value) {
        currentPage.value = page
        fetchSellerProducts(page, searchKeyword.value, selectedCategoryId.value)
      }
    }

    // 跳转到商品详情
    const goToProductDetail = (productId) => {
      router.push(`/product/${productId}`)
    }

    // 返回上一页
    const goBack = () => {
      router.back()
    }

    // 监听分类和搜索关键词变化
    watch([searchKeyword, selectedCategoryId], () => {
      // 当分类或搜索关键词改变时，重置页码并重新获取数据
      fetchSellerProducts(1, searchKeyword.value, selectedCategoryId.value)
    })

    // 监听路由参数变化
    const handleRouteChange = () => {
      sellerId.value = Number(route.params.id)
      currentPage.value = 1
      searchKeyword.value = ''
      selectedCategoryId.value = null
      loadAllData()
    }

    // 加载所有数据
    const loadAllData = async () => {
      loading.value = true
      await Promise.all([
        fetchSellerInfo(),
        fetchSellerCategories(),
        fetchSellerProducts()
      ])
      loading.value = false
    }

    onMounted(() => {
      loadAllData()
    })

    // 监听路由参数变化
    watch(() => route.params.id, (newId) => {
      if (newId && newId !== sellerId.value) {
        sellerId.value = Number(newId)
        handleRouteChange()
      }
    })

    return {
      seller,
      categories,
      products,
      loading,
      loadingProducts,
      searchKeyword,
      selectedCategoryId,
      currentPage,
      totalPages,
      handleSearch,
      handleSearchInput,
      selectCategory,
      changePage,
      goToProductDetail,
      goBack
    }
  }
}
</script>

<style scoped>
.seller-page {
  width: 100%;
  min-height: 100vh;
  padding: 20px;
  background-color: #f5f5f5;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
}

.loading-container,
.error-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 50vh;
  gap: 20px;
}

.detail-content {
  max-height: 94.3vh;
  overflow-y: auto;
  /* 为detail-content添加自定义滚动条样式 */
}

/* 自定义滚动条样式 - Webkit内核浏览器 */
.detail-content::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

.detail-content::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

.detail-content::-webkit-scrollbar-thumb {
  background: #888;
  border-radius: 4px;
}

.detail-content::-webkit-scrollbar-thumb:hover {
  background: #555;
}

.seller-content {
  max-width: 1200px;
  margin: 0 auto;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.seller-header {
  margin-bottom: 30px;
}

.back-button {
  padding: 8px 16px;
  background-color: #3498db;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
  margin-bottom: 20px;
}

.back-button:hover {
  background-color: #2980b9;
}

.seller-info {
  display: flex;
  align-items: center;
  gap: 20px;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.seller-logo {
  width: 100px;
  height: 100px;
  object-fit: cover;
  border-radius: 50%;
  border: 2px solid #e9ecef;
}

.seller-details {
  flex: 1;
}

.seller-name {
  font-size: 24px;
  font-weight: 600;
  margin: 0 0 10px 0;
  color: #333;
}

.seller-contact,
.seller-phone,
.seller-address {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

/* 搜索和分类区域 */
.search-section {
  margin-bottom: 30px;
}

.search-area {
  display: flex;
  gap: 32px;
  align-items: center;
  flex-wrap: wrap;
}

/* 搜索输入框 */
.search-input {
  width: 320px;
  height: 40px;
  padding: 0 16px;
  border: 2px solid transparent;
  border-radius: 25px;
  font-size: 14px;
  background: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(5px);
  transition: all 0.3s ease;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  outline: none;
}

.search-input:focus {
  border-color: #667eea;
  background: rgba(255, 255, 255, 1);
  transform: translateY(-2px);
  box-shadow: 0 4px 20px rgba(102, 126, 234, 0.3);
}

/* 分类标签 */
.category-tabs {
  display: flex;
  gap: 8px;
  align-items: center;
  flex-wrap: wrap;
}

.category-tab {
  padding: 8px 16px;
  border: 2px solid transparent;
  border-radius: 25px;
  font-size: 14px;
  color: #666666;
  background: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(5px);
  cursor: pointer;
  transition: all 0.3s ease;
  white-space: nowrap;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.category-tab:hover {
  border-color: #667eea;
  color: #667eea;
  transform: translateY(-2px);
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.2);
}

.category-tab.active {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-color: transparent;
  color: #ffffff;
  transform: translateY(-2px);
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
}

/* 商品列表 */
.product-list h3 {
  font-size: 18px;
  margin-bottom: 20px;
  color: #333;
}

.no-products {
  text-align: center;
  padding: 40px;
  color: #999;
  font-size: 16px;
}

.products-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 20px;
}

.product-card {
  border: 1px solid #eee;
  border-radius: 8px;
  padding: 15px;
  cursor: pointer;
  transition: all 0.3s;
  background-color: white;
}

.product-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.product-image {
  width: 100%;
  height: 200px;
  overflow: hidden;
  margin-bottom: 15px;
  border-radius: 4px;
}

.product-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s;
}

.product-card:hover .product-image img {
  transform: scale(1.05);
}

.product-info .product-name {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 10px;
  height: 40px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.product-info .product-price {
  font-size: 20px;
  font-weight: 700;
  color: #e74c3c;
  margin-bottom: 5px;
}

.product-info .product-stock {
  font-size: 12px;
  color: #999;
}

/* 分页 */
.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 20px;
  margin-top: 30px;
}

.page-btn {
  padding: 8px 16px;
  background-color: #f0f0f0;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
}

.page-btn:hover:not(:disabled) {
  background-color: #e0e0e0;
}

.page-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.page-info {
  font-size: 14px;
  color: #666;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .seller-content {
    padding: 15px;
  }

  .seller-info {
    flex-direction: column;
    text-align: center;
  }

  .seller-logo {
    width: 80px;
    height: 80px;
  }

  .products-grid {
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  }
}
</style>
